package cn.javasea.rbac.shiro.controller;

import cn.javasea.rbac.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    // 个人主页
    /**
     * @RequiresPermissions("user-home") 访问此方法必须具备的权限，和过滤器中配置的url是否有权限处理方式不一样
     *    过滤器：如果权限信息不匹配会调用到 setUnauthorizedUrl地址
     *    注解：如果权限信息不匹配，抛出异常。可以通过在异常处理类中进行处理
     */

//    @RequiresRoles()        // 访问此方法必须具备的角色
    @RequestMapping(value = "/user/home")
    public String home(){return "访问个人主页成功";}

    //添加
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String add() {
        return "添加用户成功";
    }

    //查询
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String find() {
        return "查询用户成功";
    }

    //更新
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String update(String id) {
        return "更新用户成功";
    }

    //删除
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String delete() {
        return "删除用户成功";
    }

	//用户登录
	@RequestMapping(value="/login")
    public String login(String username,String password) {
        try {
            /** 密码加密：
             *      shiro提供的md5加密
             *      Md5Hash:
             *          参数一：加密的内容
             *          参数二：盐（加密的混淆字符串）
             *          参数三：加密次数
             */
            password = new Md5Hash(password, username, 3).toString();
            // 构建token
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // 获取subject
            Subject subject = SecurityUtils.getSubject();
            // 获取session
            String sid = (String)subject.getSession().getId();
            // 执行登陆
            subject.login(token);
            return "登录成功"+sid;
        } catch (AuthenticationException e) {
            return "用户名或密码错误";
        }
    }

    @RequestMapping(value="/autherror")
    public String autherror(int code){
        return code == 1 ? "未登录" : "未授权";
    }
}
